import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/device/gateway/add_gateway/result_page.dart";
import "package:ct_pa_majordomo/pages/device/gateway/add_gateway/widgets/select_wifi.dart";
import "package:ct_pa_majordomo/pages/device/gateway/api.dart";
import "package:ct_pa_majordomo/pages/device/widgets/select_wifi.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/select_group.dart";
import "package:flutter/cupertino.dart";
import 'package:flutter/material.dart';
import "package:flutter_easyloading/flutter_easyloading.dart";
import 'package:ttlock_flutter/ttlock.dart';
import 'package:ttlock_flutter/ttgateway.dart';

class WifiPage extends StatefulWidget {
  final String mac;
  final TTGatewayScanModel gateway;
  const WifiPage({super.key, required this.mac, required this.gateway});

  @override
  State<StatefulWidget> createState() => _WifiPageState();
}

class _WifiPageState extends State<WifiPage> {
  // {"wifi": "一只猪", "rssi": -60}, {"wifi": "一只狗", "rssi": -96}
  List _wifiList = [];
  Map _wifi = {"wifi": null, "rssi": null};
  final Map _params = {
    "plugMac": null,
    "wifi": null,
    "wifiPassword": null,
    "plugName": null,
    "type": TTGatewayType.g2.index,
    "ttlockLoginPassword": null
  };
  Map _accessToken = {};

  @override
  void initState() {
    super.initState();
    setState(() {
      _params["plugMac"] = widget.mac;
    });
    // _getNearbyWifi();
    _getAccessToken();
  }

  void _getAccessToken() async {
    Map resData = await plugApi.getAccessToken();
    print("accessToken:>>>>>>>>>>>>$resData");
    setState(() {
      _accessToken = resData["data"] ?? {};
    });
  }

  Future<void> _initGateway_2() async {
    Map params = Map();
    params["wifi"] = _params["wifi"];
    params["gatewayName"] = widget.gateway.gatewayName;
    params["wifiPassword"] = _params["wifiPassword"];
    params["type"] = _params["type"];
    params["uid"] = _accessToken["uid"];
    params["ttlockLoginPassword"] = _accessToken["password"];
    print("params:>>>$params");
    EasyLoading.show();

    TTGateway.init(params, (map) async {
      print("网关添加结果");
      print(map);
      await _addGateway();
      EasyLoading.dismiss();
      if (context.mounted) {
        Navigator.push(
          context,
          CupertinoPageRoute(
            builder: (BuildContext context) {
              return const ResultPage(result: ResultType.success,);
            },
          ),
        );
      }
    }, (errorCode, errorMsg) {
      EasyLoading.showToast("errorCode:$errorCode msg:$errorMsg");
      if (errorCode == TTGatewayError.notConnect ||
          errorCode == TTGatewayError.disconnect) {
        print("Please repower  and connect the gateway again");
      }
    });
  }

  Future<void> _addGateway() async {
    Map<String, dynamic> params = {
      "plugName": _params["plugName"],
      "plugMac": _params["plugMac"],
    };
    await plugApi.addGateway(params);
  }

  void _getNearbyWifi() {
    try {
      TTGateway.getNearbyWifi((finished, wifiList) {
        print("finished: ${finished}》》》》》》》》》》》》${wifiList}");
        setState(() {
          _wifiList = wifiList;
        });
      }, (errorCode, errorMsg) {
        EasyLoading.showToast("$errorCode:>>>$errorMsg");
      });
    } catch(error) {
      print("wifi scan error >>> $error");
    }
  }

  // void _pushGatewayPage(String wifi) {
  //   Navigator.push(context,
  //       new MaterialPageRoute(builder: (BuildContext context) {
  //         return GatewayPage(type: TTGatewayType.g2, wifi: wifi);
  //       }));
  // }

  bool _validate(Map value) {
    // return !value.values.any((value) => Utils.isEmpty(value));
    if (_params["wifi"] == null || _params["wifiPassword"] == null || _params["wifiPassword"]!.length == 0) {
      // EasyLoading.showToast('"wifi or password cant be empty');
      return false;
    }
    return true;
  }

  Widget getList() {
    return ListView.builder(
        itemCount: _wifiList.length,
        padding: new EdgeInsets.all(5.0),
        itemExtent: 50.0,
        itemBuilder: (context, index) {
          Map wifiMap = _wifiList[index];
          int rssi = wifiMap['rssi'];
          return ListTile(
            title: Text(wifiMap['wifi']),
            subtitle: Text('rssi:$rssi'),
            onTap: () {
              Map wifiMap = _wifiList[index];
              String wifi = wifiMap['wifi'];
              print(wifi);
              // _pushGatewayPage(wifi);
            },
          );
        }
    );
  }

  void _selectWifi() async {
    final result = await Stacker.pushNamed(
      Keys.DEVICE_SELECT_WIFI, 
      arguments: {
        'type': ConfigWifiType.gateway,
      }
    );
    
    if (result != null && result is Map) {
      setState(() {
        _wifi = result;
        _params["wifi"] = _wifi["wifi"];
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        iconTheme: const IconThemeData(color: Colors.white),
        title: const Text("配置网络", style: TextStyle(color: Colors.white),),
        centerTitle: true,
        backgroundColor: ThemeVars.colorPrimary,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios_new),
          onPressed: () {
            TTGateway.disconnect(widget.mac, () {
              Navigator.pop(context);
            });
          },
        ),
      ),
      body: ListView(
        padding: const EdgeInsets.all(ThemeVars.paddingPage),
        children: [
          MenuBlock(
            borderRadius: BorderRadius.circular(5),
            items: [
              MenuBlockItem(
                text: "WiFi名称",
                showArrow: true,
                suffix: _params["wifi"] != null ? Text(_params["wifi"]) : const Text("请选择WiFi", style: TextStyle(color: ThemeVars.colorTextTer),),
                onTap: () {
                  _selectWifi();
                }
              ),
              MenuBlockItem(
                text: "WiFi密码",
                showArrow: false,
                suffix: TextField(
                  textAlign: TextAlign.right,
                  decoration: const InputDecoration(
                    hintText: "请输入WiFi密码",
                    border: InputBorder.none,
                  ),
                  onChanged: (value) {
                    setState(() {
                      _params["wifiPassword"] = value;
                    });
                  },
                ),
              ),
              MenuBlockItem(
                text: "网关名称",
                showArrow: false,
                suffix: TextField(
                  textAlign: TextAlign.right,
                  decoration: const InputDecoration(
                    hintText: "请输入网关名称",
                    border: InputBorder.none,
                  ),
                  onChanged: (value) {
                    setState(() {
                      _params["plugName"] = value;
                    });
                  },
                ),
              ),
            ],
          ),
          const SizedBox(height: 60,),
          Button(
            type: ButtonType.primary,
            onPressed: _validate(_params) ? () {
              _initGateway_2();
            } : null,
            child: const Text("下一步"),
          ),
        ],
      ),
    );
  }
}
